import os
import csv
import numpy as np
from base_logger import get_logger


# 在函数的参数中加上几个默认参数，在以后把这段代码模块化的时候很有帮助
def main(filenames_=None, filename_output='M_inv.csv'):
    mats = {}
    # 如果有指定文件名就用那些文件名，没有指定就使用默认
    filename = 'M.csv' if filenames_ is None else filenames_
    if not os.path.exists(filename):
        logger.error('File %s not found!' % filename)
        return
    mat = []
    try:
        with open(filename, 'r') as f:
            reader = csv.reader(f)
            for row in reader:
                try:
                    data = [float(x) for x in row]
                except ValueError as e:
                    logger.error("Can't convert something to 'float'! %s" % str(e))
                    return
                mat.append(data)
    except IOError:
        logger.error('IOError when reading %s!' % filename)
        return
    # 转换成numpy的格式，方便进行矩阵运算
    mat = np.array(mat)
    # 直接打印矩阵也会帮你优化对齐
    print(filename, ":\n", mat)
    try:
        # numpy真的太方便了~
        c = np.linalg.inv(mat)
    except np.linalg.LinAlgError as e:
        logger.error('numpy.linalg.LinAlgError when trying to calc M^{-1}: %s' % str(e))
        return
    print('M^{-1} =')
    print(c)
    # numpy转回python的list格式
    c_list = c.tolist()
    print('c_list:', c_list)
    try:
        # 用newline=''是因为csv库写入的时候不知道为啥会多出空行...
        with open(filename_output, 'w', newline='') as f:
            writer = csv.writer(f)
            writer.writerows(c_list)
    except IOError:
        logger.error('IOError when writing %s!' % filename_output)
        return
    logger.info('Write to %s done.' % filename_output)


logger = get_logger(__name__)
if __name__ == '__main__':
    main()
